/**
 * 拆分 Reducer（combineReducers）
 * 参考：https://github.com/kenberkeley/redux-simple-tutorial/blob/master/redux-advanced-tutorial.md
 * 
 * 问题：所有 reducer 全部写在一起，随着不断引入新的模块，reducer 会越来越臃肿，其可操作性、可维护性、可扩展性越来越低
 * 
//源 reducer
var initState = {
  counter: 0,
  todos: []
}

function reducer(state, action) {
  if (!state) state = initState

  switch (action.type) {
    case 'ADD_TODO':
      var nextState = _.cloneDeep(state) // 用到了 lodash 的深克隆
      nextState.todos.push(action.payload) 
      return nextState

    default:
      return state
  }
}


//引入新的模块的 reducer
var initState = { counter: 0, todos: [] }

function reducer(state, action) {
  if (!state) return initState // 若是初始化可立即返回应用初始状态
  var nextState = _.cloneDeep(state) // 否则二话不说先克隆

  switch (action.type) {
    case 'ADD_TODO': // 新增待办事项
      nextState.todos.push(action.payload) 
      break   
    case 'INCREMENT': // 计数器加 1
      nextState.counter = nextState.counter + 1
      break
  }
  return nextState
}

 * 
 * 
 * 需求：拆分 Reducer
 */

// 目录结构如下
// reducers/
//    ├── index.js <-------------- combineReducers (生成 rootReducer)
//    ├── counterReducer.js
//    ├── todoReducers/
//            ├── index.js <------ combineReducers
//            ├── optTimeReducer.js
//            ├── todoListReducer.js


//dispatch 分发流
//
//                                  counterReducer(counter, action) -------------------- counter
//                               ↗                                                              ↘
// rootReducer(state, action) —→∑     ↗ optTimeReducer(optTime, action) ------ optTime ↘         nextState
//                               ↘—→∑                                                    todo  ↗
//                                    ↘ todoListReducer(todoList,action) ----- todoList ↗


// 注：左侧表示 dispatch 分发流，∑ 表示 combineReducers；右侧表示各实体 reducer 的返回值，最后汇总整合成 nextState


/**
 * 编码
 */
import { createStore } from 'redux'
import rootReducer from './reducers/';
import counterAction from './actions/counterActions.js';
import * as todoActions from './actions/todoActions';

var store = createStore(rootReducer);

console.log(store.getState());
store.dispatch(counterAction(17));
console.log(store.getState());
store.dispatch(todoActions.addTodo("任务"));
console.log(store.getState());
store.dispatch(todoActions.addOptTime());
console.log(store.getState());
